//
// Created by chizuru on 2025/9/2.
//

#include "RegisterWriteCommand.h"

RegisterWriteCommand::RegisterWriteCommand(CameraDevice &comm, uint16_t addr, uint32_t value, RetryPolicy rp, bool captureOriginal)
        : comm(comm)
        , _addr(addr)
        , _value(value)
        , rp(rp)
        , captureOriginal(captureOriginal) {

}

bool RegisterWriteCommand::execute() {
    if (captureOriginal) {
        auto v = comm.readRegister(_addr);
        if (!v)
            return false;
        originalValue = *v;
        haveOriginal = true;
    }
    bool ok = comm.writeRegister(_addr, _value);
    if (!ok)
        return false;
    done = true;
    return true;
}


bool RegisterWriteCommand::undo() {
    // 只有当本命令确实完成了写操作，才尝试恢复原值
    if (!done) return true;
    if (haveOriginal) {
        bool ok = comm.writeRegister(_addr, originalValue);
        if (ok) done = false; // 恢复成功，标记为已回滚
        return ok;
    }
    return true;
}

uint16_t RegisterWriteCommand::addr() const { return _addr; }

uint32_t RegisterWriteCommand::value() const { return _value; }